package com.myblog.services.impl;


import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.myblog.Utils.BeanCopyUtils;
import com.myblog.Utils.WebUtils;
import com.myblog.domain.GlobalResponse;

import com.myblog.domain.Vo.CategoryVo;
import com.myblog.domain.Vo.ExcelCategoryVo;
import com.myblog.domain.Vo.PageVo;
import com.myblog.domain.contants.GlobalConstants;
import com.myblog.domain.dto.CategoryDto;
import com.myblog.domain.entity.Article;
import com.myblog.domain.entity.Category;
import com.myblog.domain.entity.enums.GlobalResponseEnum;
import com.myblog.mapper.CategoryMapper;
import com.myblog.services.ArticleService;
import com.myblog.services.CategoryService;
import io.jsonwebtoken.lang.Strings;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.myblog.domain.contants.GlobalConstants.ARTICLE_STATUS_NORMAL;

/**
* @author Administrator
* @description 针对表【sg_category(分类表)】的数据库操作Service实现
* @createDate 2022-09-26 10:22:01
*/
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    /*
     *获取分类列表
     *只需要分类的id和分类的信息即可
     *分类下必须有文章才可显示
     *必须是正常状态
     */
    @Resource
    ArticleService articleService;
    @Override
    public GlobalResponse getCategoryList() {
        //先查询文章表,必须是已发布的文章
        LambdaQueryWrapper<Article> articleQueryWrapper=new LambdaQueryWrapper<>();
        articleQueryWrapper.eq(Article::getStatus,ARTICLE_STATUS_NORMAL);
        List<Article> list = articleService.list(articleQueryWrapper);
        //用stream流来读取List并去重
        Set<Long> categoryIdSet = list.stream()
                .map(article -> article.getCategoryId())
                .collect(Collectors.toSet());
        //获取分类列表
        List<Category> categories = listByIds(categoryIdSet);
        //必须得是正常发布的列表，用流来改进
        List<Category> normalCategories = categories.stream()
                .filter(category -> GlobalConstants.CATEGORY_STATUS_NORMAL.equals(category.getStatus()))
                .collect(Collectors.toList());
        //Bean拷贝
        List<CategoryVo> categoryVos = BeanCopyUtils.copyBeanList(normalCategories, CategoryVo.class);

        return GlobalResponse.ok(categoryVos);
    }

    @Override
    public GlobalResponse getAllCategoryList() {
        //必须是状态正常的list
        LambdaQueryWrapper<Category> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Category::getStatus,GlobalConstants.STATUS_NORMAL);
        List<Category> categoryList = list(queryWrapper);
        List<CategoryVo> categoryVos = BeanCopyUtils.copyBeanList(categoryList, CategoryVo.class);
        return GlobalResponse.ok(categoryVos);
    }

    @Override
    public void AllListToExcel(HttpServletResponse response) {
        try {

            WebUtils.setDownLoadHeader("全部分类.xlsx",response);
            List<Category> categoryList = list();
            List<ExcelCategoryVo> excelCategoryVos = BeanCopyUtils.copyBeanList(categoryList, ExcelCategoryVo.class);

            EasyExcel.write(response.getOutputStream(), ExcelCategoryVo.class).autoCloseStream(Boolean.FALSE).sheet("分类导出")
                    .doWrite(excelCategoryVos);

        } catch (Exception e) {
            GlobalResponse res=GlobalResponse.error(GlobalResponseEnum.ERROR);
            WebUtils.renderString(response, JSON.toJSONString(res));
        }

    }

    @Override
    public GlobalResponse getList(Integer pageNum, Integer pageSize, String name, String status) {
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper=new LambdaQueryWrapper<>();
        categoryLambdaQueryWrapper.like(Strings.hasText(name),Category::getName,name);
        categoryLambdaQueryWrapper.eq(Strings.hasText(status),Category::getStatus,status);
        Page<Category> page=new Page<>(pageNum,pageSize);
        page(page,categoryLambdaQueryWrapper);
        List<Category> categoryList = page.getRecords();
        List<CategoryVo> categoryVos = BeanCopyUtils.copyBeanList(categoryList, CategoryVo.class);

        return GlobalResponse.ok(new PageVo(categoryVos,page.getTotal()));
    }

    @Override
    public GlobalResponse addCategory(CategoryDto categoryDto) {
        Category category = BeanCopyUtils.copyBean(categoryDto, Category.class);
        if(!save(category)){
            return GlobalResponse.error();
        }
        return GlobalResponse.ok();
    }


}
